<template>
  <div class="my-application">
    <el-tabs v-model="activeTab" @tab-change="handleTabClick">

      <el-tab-pane label="迁入企业申请" name="immigrantEnterprise">
        <div class="application-card" v-if="immigrantEnterpriseData.length > 0">
          <el-card v-for="item in immigrantEnterpriseData" :key="item.id" class="mb-4">
            <template #header>
              <div class="card-header">
                <span>申请信息</span>
                <div class="card-actions">
                  <el-button  type="warning" v-if="item.status > 0" link @click="handleprint(item.id, 'immigrantEnterprise')">打印</el-button>
                  <el-button
                    v-if="item.status === 0"
                    type="primary"
                    link
                    @click="handleEdit(item, 'immigrantEnterprise')"
                  >编辑</el-button>
                  <el-button
                      v-if="item.status === 1"
                      type="danger"
                      link
                      @click="handleWithdraw(item, 'immigrantEnterprise')"
                  >撤回</el-button>
                  <el-button
                    v-if="item.status === 0"
                    type="danger"
                    link
                    @click="handleDelete(item.id, 'immigrantEnterprise')"
                  >删除</el-button>
                </div>
              </div>
            </template>
            <div class="card-content">
              <div class="info-item">
                <span class="label">企业名称：</span>
                <span class="value">{{ item.enterpriseName }}</span>
              </div>
              <div class="info-item">
                <span class="label">申请时间：</span>
                <span class="value">{{ formatDate(item.establishmentDate) }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态：</span>
                <el-tag v-if="item.status === 0">未提交</el-tag>
                <el-tag type="primary" v-if="item.status === 1">已提交</el-tag>
                <el-tag type="success" v-if="item.status === 2">审核通过</el-tag>
                <el-tag type="danger" v-if="item.status === 3">审核失败</el-tag>
              </div>
            </div>
          </el-card>
        </div>
        <el-empty v-else description="暂无申请记录" />
      </el-tab-pane>


      <el-tab-pane label="新成立企业申请" name="firstEnterprise">
        <div class="application-card" v-if="firstEnterpriseData.length > 0">
          <el-card v-for="item in firstEnterpriseData" :key="item.id" class="mb-4">
            <template #header>
              <div class="card-header">
                <span>申请信息</span>
                <div class="card-actions">
                  <el-button type="warning"  v-if="item.status > 0" link @click="handleprint(item.id, 'firstEnterprise')">打印</el-button>
                  <el-button
                      v-if="item.status === 0"
                      type="primary"
                      link
                      @click="handleEdit(item, 'firstEnterprise')"
                  >编辑</el-button>
                  <el-button
                      v-if="item.status === 1"
                      type="danger"
                      link
                      @click="handleWithdraw(item, 'firstEnterprise')"
                  >撤回</el-button>
                  <el-button
                      v-if="item.status === 0"
                      type="danger"
                      link
                      @click="handleDelete(item.id, 'firstEnterprise')"
                  >删除</el-button>
                </div>
              </div>
            </template>
            <div class="card-content">
              <div class="info-item">
                <span class="label">企业名称：</span>
                <span class="value">{{ item.itemName }}</span>
              </div>
              <div class="info-item">
                <span class="label">申请时间：</span>
                <span class="value">{{ formatDate(item.applyDate) }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态：</span>
                <el-tag v-if="item.status === 0">未提交</el-tag>
                <el-tag type="primary" v-if="item.status === 1">已提交</el-tag>
                <el-tag type="success" v-if="item.status === 2">审核通过</el-tag>
                <el-tag type="danger" v-if="item.status === 3">审核失败</el-tag>
              </div>
            </div>
          </el-card>
        </div>
        <el-empty v-else description="暂无申请记录" />
      </el-tab-pane>


      <el-tab-pane label="众创空间入驻申请" name="residency">
        <div class="application-card" v-if="residencyData.length > 0">
          <el-card v-for="item in residencyData" :key="item.id" class="mb-4">
            <template #header>
              <div class="card-header">
                <span>申请信息</span>
                <div class="card-actions">
                  <el-button type="warning" v-if="item.status > 0" link @click="handleprint(item.id, 'residency')">打印</el-button>
                  <el-button
                    v-if="item.status === 0"
                    type="primary"
                    link
                    @click="handleEdit(item, 'residency')"
                  >编辑</el-button>
                  <el-button
                      v-if="item.status === 1"
                      type="danger"
                      link
                      @click="handleWithdraw(item, 'residency')"
                  >撤回</el-button>
                  <el-button
                    v-if="item.status === 0"
                    type="danger"
                    link
                    @click="handleDelete(item.id, 'residency')"
                  >删除</el-button>
                </div>
              </div>
            </template>
            <div class="card-content">
              <div class="info-item">
                <span class="label">申请名称：</span>
                <span class="value">{{ item.name }}</span>
              </div>
              <div class="info-item">
                <span class="label">申请时间：</span>
                <span class="value">{{ formatDate(item.applyDate) }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态：</span>
                <el-tag v-if="item.status === 0">未提交</el-tag>
                <el-tag type="primary" v-if="item.status === 1">已提交</el-tag>
                <el-tag type="success" v-if="item.status === 2">审核通过</el-tag>
                <el-tag type="danger" v-if="item.status === 3">审核失败</el-tag>
              </div>
            </div>
          </el-card>
        </div>
        <el-empty v-else description="暂无申请记录" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import {
  getMyEnterpriseApplicationList,
  getMyImmigrantApplicationList,
  getMyApplicationList,
  delApplication,
  delImmigrantApplication,
  editEnterpriseApplication,
  editImmigrantApplication, delEnterpriseApplication, delApplicationFromIds, editApplication,
} from '@/api/enterpeise';
import { getLoginUserId } from '@/utils/storage';
import dayjs from 'dayjs';
import type { AjaxResult } from '@/types/resultTypes';

const router = useRouter();
const activeTab = ref('immigrantEnterprise');

// 列表数据
const firstEnterpriseData = ref<any[]>([]);
const immigrantEnterpriseData = ref<any[]>([]);
const residencyData = ref<any[]>([]);

// 获取新成立企业申请列表
const getFirstEnterpriseList = async () => {
  try {
    const res = await getMyEnterpriseApplicationList() as unknown as AjaxResult<any>;
    if (res.code === 200) {
      firstEnterpriseData.value = Array.isArray(res.data) ? res.data : [];
    } else {
      ElMessage.error({
        message: res.msg,
      });
    }
  } catch (error) {
    console.error('获取新成立企业申请列表失败:', error);
  }
};

// 获取迁入企业申请列表
const getImmigrantEnterpriseList = async () => {
  try {
    const res = await getMyImmigrantApplicationList() as unknown as AjaxResult<any>;
    if (res.code === 200) {
      immigrantEnterpriseData.value = Array.isArray(res.data) ? res.data : [];
    } else {
      ElMessage.error({
        message: res.msg,
      });
    }
  } catch (error) {
    console.error('获取迁入企业申请列表失败:', error);
  }
};

// 获取众创空间入驻申请列表
const getResidencyList = async () => {
  try {
    const res = await getMyApplicationList() as unknown as AjaxResult<any>;
    if (res.code === 200) {
      residencyData.value = Array.isArray(res.data) ? res.data : [];
    } else {
      ElMessage.error({
        message: res.msg,
      });
    }
  } catch (error) {
    console.error('获取众创空间入驻申请列表失败:', error);
  }
};

// 处理标签页切换
const handleTabClick = () => {
  console.log(activeTab.value);
  switch (activeTab.value) {
    case 'firstEnterprise':
      getFirstEnterpriseList();
      break;
    case 'immigrantEnterprise':
      getImmigrantEnterpriseList();
      break;
    case 'residency':
      getResidencyList();
      break;
  }
};

// 打印
const handleprint = (id: any, type: string) => {
  // 确保ID是BigInt类型
  let bigIntId;
  try {
    bigIntId = BigInt(id);
  } catch (error) {
    console.error('错误：ID无法转换为BigInt: ' + error);
    return;
  }

  switch (type) {
    case 'immigrantEnterprise': // 迁入企业申请
      const immigrantEnterpriseRoute = router.resolve({
        name: 'immigrantenterpriseprint',
        query: { id: bigIntId.toString() },
      });
      window.open(immigrantEnterpriseRoute.href, '_blank');
      break;

    case 'firstEnterprise': // 新成立企业申请
      const firstEnterpriseRoute = router.resolve({
        name: 'firstenterpriseprint',
        query: { id: bigIntId.toString() },
      });
      window.open(firstEnterpriseRoute.href, '_blank');
      break;
    case 'residency': // 众创空间入驻申请
      const residencyRoute = router.resolve({
        name: 'residencyapplicationprint',
        query: { id: bigIntId.toString() },
      });
      window.open(residencyRoute.href, '_blank');
      break;
  }
};

// 编辑申请
const handleEdit = (row: any, type: string) => {
  switch (type) {
    case 'immigrantEnterprise': // 迁入企业申请
      router.push(`/personal-center/enterprise-settlement/enterprise/immigrant?id=${row.id}`);
      break;

    case 'firstEnterprise': // 初创企业申请
      router.push(`/personal-center/enterprise-settlement/enterprise/first?id=${row.id}`);
      break;

    case 'residency': // 众创空间入驻申请
      const applicantType = String(row.type);
      // 根据申请类型判断跳转到哪个表单
      if (applicantType === '0' ) {
        router.push(`/personal-center/enterprise-settlement/residency-application/student?id=${row.id}`);
        break;
      } else if (applicantType === '1') {
        router.push(`/personal-center/enterprise-settlement/residency-application/teacher?id=${row.id}`);
        break;
      } else if (applicantType === '2' ) {
        router.push(`/personal-center/enterprise-settlement/residency-application/teacher?id=${row.id}`);
        break;
      }
      break;
  }
};

// 撤回操作
const handleWithdraw = async (item: any, type: string) => {
  try {
    await ElMessageBox.confirm('确定要撤回该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    let res;
    const updateData = {
      id: item.id,
      status: 0 // 将状态更新为0（未提交）
    };

    switch (type) {
      case 'immigrantEnterprise':
        res = await editImmigrantApplication(updateData) as unknown as AjaxResult<any>;
        break;
      case 'firstEnterprise':
        res = await editEnterpriseApplication(updateData) as unknown as AjaxResult<any>;
        break;
      case 'residency':
        // 众创空间入驻申请的撤回API需要根据实际情况调整
        res = await editApplication(updateData) as unknown as AjaxResult<any>;
        break;
    }

    if (res?.code === 200) {
      ElMessage.success('撤回成功');
      handleTabClick(); // 刷新列表
    } else {
      ElMessage.error(res?.msg || '撤回失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回失败:', error);
      ElMessage.error('撤回失败');
    }
  }
};

// 删除申请
const handleDelete = async (id: string | number, type: string) => {
  try {
    await ElMessageBox.confirm('确定要删除该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    let res;
    switch (type) {
      case 'firstEnterprise':
        res = await delEnterpriseApplication(id.toString()) as unknown as AjaxResult<any>;
        break;
      case 'immigrantEnterprise':
        res = await delImmigrantApplication(id.toString()) as unknown as AjaxResult<any>;
        break;
      case 'residency':
        res = await delApplicationFromIds(id.toString()) as unknown as AjaxResult<any>;
        break;
    }

    if (res?.code === 200) {
      ElMessage.success('删除成功');
      handleTabClick(); // 刷新列表
    } else {
      ElMessage.error(res?.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除申请失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 格式化时间
const formatDate = (date: string | number | Date | null | undefined) => {
  if (!date) return '';
  return dayjs(date).format('YYYY-MM-DD');
};

// 初始化
onMounted(() => {
  handleTabClick();
});
</script>

<style lang="scss" scoped>
.my-application {
  width: 100%;
  padding: 20px;

  :deep(.el-tabs__content) {
    padding: 20px 0;
  }

  .application-card {
    max-width: 1000px;
    margin: 0 auto;

    .mb-4 {
      margin-bottom: 16px;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .card-actions {
        display: flex;
        gap: 10px;
      }
    }

    .card-content {
      .info-item {
        margin-bottom: 16px;
        display: flex;
        align-items: center;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          width: 100px;
          color: #606266;
        }

        .value {
          color: #303133;
        }
      }
    }
  }
}
</style>
